package com.xuan.handler;

import com.alibaba.fastjson.JSON;
import com.xuan.entity.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

import static com.xuan.constants.CommonConstants.USER_TOKEN_PREFIX;

@Slf4j(topic = "LoginHandler")
@Component
public class LoginHandler implements HandlerInterceptor {
    private StringRedisTemplate redisTemplate;
    public LoginHandler(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (HttpMethod.OPTIONS.matches(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        // 增强 Token 处理
        String authHeader = request.getHeader("Authorization");
        if (!StringUtils.hasText(authHeader) || !authHeader.startsWith("Bearer ")) {
            sendError(response, 401, "认证头格式错误，请使用 Bearer Token 格式");
            return false;
        }
        String token = authHeader.substring(7);

        // 从redis中获取token对应的value 判断是不是当前用户
        String redisKey = USER_TOKEN_PREFIX + token;
        log.debug("完整Redis Key: {}", redisKey);
        Long userId;
        try {
            String value = redisTemplate.opsForValue().get(redisKey);
            if (value == null || value.isEmpty()) {
                sendError(response, 401, "没有权限");
            }
            userId = Long.valueOf(value);
            log.debug("Redis返回值: {}", userId);
        } catch (RedisConnectionFailureException e) {
            log.error("Redis连接失败", e);
            sendError(response, 503, "服务暂不可用");
            return false;
        }
        String header = request.getHeader("id");
        if (header == null || header.isEmpty()) {
            System.out.println("请求头没有id字段");
            sendError(response, 401, "没有权限");
        }
        Long id = Long.valueOf(header);
        if (!id.equals(userId)) {
            System.out.println("不是当前登录的用户");
            sendError(response, 401, "没有权限");
        }
        if (!StringUtils.hasText(userId.toString())) {
            log.warn("无效Token: {}", token);
            sendError(response, 401, "会话已过期");
            return false;
        }
        return true;
    }

    private void sendError(HttpServletResponse response, int code, String msg) {
        try {
            response.setStatus(code);
            response.setContentType("application/json");
            try (OutputStream os = response.getOutputStream()) {
                byte[] bytes = JSON.toJSONString(Result.error(msg)).getBytes(StandardCharsets.UTF_8);
                os.write(bytes);
                os.flush();
            }
        } catch (IOException e) {
            log.error("响应写入失败", e);
        }
    }

}
